package com.safe.utils;

import com.safe.core.Constant;
import org.apache.commons.lang.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * Java中日期的经常有一下五个方面：
 * 1、创建日期
 * 2、日期格式化显示
 * 3、日期的转换（主要是和字符串之间的相互转换）
 * 4、日期中年、月、日、时、分、秒、星期、月份等获取
 * 5、日期的大小比较、日期的加减。
 *
 * @author Administrator
 */
public class DateUtils {

    public static void main(String[] args) throws ParseException {
        // System.out.println(getWaitTime(1527746942000L, 1527747542000L));
    }

    // 获取当前日期
    public static String getDate() {
        Calendar now = Calendar.getInstance();
        String year = now.get(Calendar.YEAR) + "";
        String month = (now.get(Calendar.MONTH) + 1) + "";
        String day = (now.get(Calendar.DAY_OF_MONTH)) + "";

        return year + "-" + month + "-" + day;
    }

    public static Date dateAddDay(Date date, int day) {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(date);
        gc.add(GregorianCalendar.DATE, day);
        return gc.getTime();
    }

    public static Date dateAddMonth(Date date, int m) {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(date);
        gc.add(GregorianCalendar.MONTH, m);
        return gc.getTime();
    }

    /**
     * 根据传入的周数查询指定周的周一开始时间和周五的结束时间
     *
     * @param weekTurn 指定的周数
     * @return 周一的开始时间和周五的结束时间
     */
    public static Long[] getWeekDate(Integer weekTurn) {
        Long[] result = new Long[2];
        SimpleDateFormat sdf = new SimpleDateFormat(Constant.TIME_FORMAT_DATE); //设置时间格式
        Calendar cal = Calendar.getInstance();

        // 根据weekTurn判断当前周的日期
        if (null != weekTurn && weekTurn < 0) {
            // 代表查看的是过去周的日期
            cal.setTime(getDateBefore(new Date(), weekTurn * 7 * -1));
        } else {
            // 代表查看的是本周的日期
            cal.setTime(new Date());
        }

        //判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);//获得当前日期是一个星期的第几天
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }

        cal.setFirstDayOfWeek(Calendar.MONDAY);//设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        int day = cal.get(Calendar.DAY_OF_WEEK);//获得当前日期是一个星期的第几天

        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);//根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        String impTimeBegin = sdf.format(cal.getTime());
        result[0] = stringToLongWithFormat(impTimeBegin + " 00:00", Constant.TIME_FORMAT_ALL);

        cal.add(Calendar.DATE, 4);
        String impTimeEnd = sdf.format(cal.getTime());
        result[1] = stringToLongWithFormat(impTimeEnd + " 23:59", Constant.TIME_FORMAT_ALL);

        return result;
    }

    /**
     * 根据传入的周数查询指定周的周一至周五的日期
     *
     * @param weekTurn 指定的周数
     * @return 周一至周五的日期
     */
    public static String[] getAllDateByWeekTurn(Integer weekTurn) {
        String[] result = new String[7];
        SimpleDateFormat sdf = new SimpleDateFormat(Constant.TIME_FORMAT_DATE); //设置时间格式
        Calendar cal = Calendar.getInstance();

        // 根据weekTurn判断当前周的日期
        if (null != weekTurn && weekTurn != 0) {
            // 代表查看的是过去周的日期
            cal.setTime(getDateBefore(new Date(), weekTurn * 7));
        } else {
            // 代表查看的是本周的日期
            cal.setTime(new Date());
        }

        //判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);//获得当前日期是一个星期的第几天
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }

        cal.setFirstDayOfWeek(Calendar.MONDAY);//设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        int day = cal.get(Calendar.DAY_OF_WEEK);//获得当前日期是一个星期的第几天

        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);//根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        result[0] = sdf.format(cal.getTime());

        cal.add(Calendar.DATE, 1);
        result[1] = sdf.format(cal.getTime());

        cal.add(Calendar.DATE, 1);
        result[2] = sdf.format(cal.getTime());

        cal.add(Calendar.DATE, 1);
        result[3] = sdf.format(cal.getTime());

        cal.add(Calendar.DATE, 1);
        result[4] = sdf.format(cal.getTime());

        cal.add(Calendar.DATE, 1);
        result[5] = sdf.format(cal.getTime());

        cal.add(Calendar.DATE, 1);
        result[6] = sdf.format(cal.getTime());

        return result;
    }

    /**
     * 得到几天前的时间
     */
    public static Long[] getLongBefore(Integer day) {
        Long[] time = new Long[2];
        Calendar now = Calendar.getInstance();
        now.setTime(new Date());
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        String date = DateUtils.dateToStringWithFormat(now.getTime(), Constant.TIME_FORMAT_DATE);

        time[0] = DateUtils.stringToLongWithFormat(date + " 00:00:00", Constant.TIME_FORMAT_DEFAULT);
        time[1] = DateUtils.stringToLongWithFormat(date + " 23:59:59", Constant.TIME_FORMAT_DEFAULT);

        return time;
    }

    /**
     * 得到几天前的时间
     */
    public static Date getDateBefore(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        return now.getTime();
    }

    public static Integer getYear(Date date) {
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        return now.get(Calendar.YEAR);
    }

    public static Integer getMonth(Date date) {

        Calendar now = Calendar.getInstance();
        now.setTime(date);
        return now.get(Calendar.MONTH) + 1;
    }

    /**
     * 当月天数
     *
     * @return
     */
    public static Integer getDays(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * 将日转换成,format格式的日期字符串
     *
     * @param date   new Date()
     * @param format yyyy-MM-dd
     * @return
     */
    public static String dateToStringWithFormat(Date date, String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(date);
    }

    /**
     * 将日期字符串转换成,format格式的日期
     *
     * @param date   日期字符串
     * @param format 日期格式:yyyy-MM-dd
     * @return
     * @throws ParseException
     */
    public static Date stringToDateWithFormat(String date, String format)
            throws ParseException {
        if (StringUtils.isBlank(date)) {
            return null;
        }
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.parse(date);
    }

    public static Long stringToLongWithFormat(String date, String format) {
        if (StringUtils.isBlank(date)) {
            return null;
        }
        try {
            SimpleDateFormat df = new SimpleDateFormat(format);
            return df.parse(date).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String LongToStringWithFormat(Long time, String format) {
        if (null == time) {
            return "";
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.format(time);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static Date getDateWithDay(Integer day, Integer flag) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, day);
        Date finallyDate = null;
        try {
            String days = DateUtils.dateToStringWithFormat(calendar.getTime(), Constant.TIME_FORMAT_DATE);
            if (flag == 0) {
                finallyDate = DateUtils.stringToDateWithFormat(days + " 00:00:00", Constant.TIME_FORMAT_DEFAULT);
            } else {
                finallyDate = DateUtils.stringToDateWithFormat(days + " 23:59:59", Constant.TIME_FORMAT_DEFAULT);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return finallyDate;
    }

    /**
     * 判断当前日期是星期几
     */
    public static int dayForWeek() {
        Calendar c = Calendar.getInstance();
        if (c.get(Calendar.DAY_OF_WEEK) - 1 == 0) {
            return 7;
        } else {
            return c.get(Calendar.DAY_OF_WEEK) - 1;
        }
    }

    /**
     * 获取前月第一天
     */
    public static Long getPrevStartTimeWithMonth() {
        SimpleDateFormat format = new SimpleDateFormat(Constant.TIME_FORMAT_DATE);
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, -1);
        c.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
        String time = format.format(c.getTime()) + " 00:00:00";
        return stringToLongWithFormat(time, Constant.TIME_FORMAT_DEFAULT);
    }

    /**
     * 获取前月最后一天
     */
    public static Long getPrevEndTimeWithMonth() {
        SimpleDateFormat format = new SimpleDateFormat(Constant.TIME_FORMAT_DATE);
        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.DAY_OF_MONTH, 0);//设置为1号,当前日期既为本月第一天
        String time = format.format(ca.getTime()) + " 23:59:59";
        return stringToLongWithFormat(time, Constant.TIME_FORMAT_DEFAULT);
    }

    /**
     * 获取当月第一天
     */
    public static Long getStartTimeWithMonth() {
        SimpleDateFormat format = new SimpleDateFormat(Constant.TIME_FORMAT_DATE);
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
        String time = format.format(c.getTime()) + " 00:00:00";
        return stringToLongWithFormat(time, Constant.TIME_FORMAT_DEFAULT);
    }

    /**
     * 获取当月最后一天
     */
    public static Long getEndTimeWithMonth() {
        SimpleDateFormat format = new SimpleDateFormat(Constant.TIME_FORMAT_DATE);
        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
        String time = format.format(ca.getTime()) + " 23:59:59";
        return stringToLongWithFormat(time, Constant.TIME_FORMAT_DEFAULT);
    }

    public static Boolean isOverTime(Long time, Integer minute) {
        return (System.currentTimeMillis() - time) / (1000 * 60) < minute;
    }

    public static Integer getWaitTime(Long startTime, Long endTime) {
        return Integer.parseInt((endTime - startTime) / (1000 * 60) + "");
    }

    public static Integer getWaitTimeWithSecond(Long startTime, Long endTime) {
        return Integer.parseInt((endTime - startTime) / (1000) + "");
    }

    /**
     * 功能：判断字符串是否为日期格式
     */
    public static boolean isDate(String strDate) {
        if (StringUtils.isBlank(strDate)) {
            return false;
        }

        String[] dates = strDate.split(":");
        if (dates.length != 2) {
            return false;
        }

        if (StringUtils.isBlank(dates[0]) || StringUtils.isBlank(dates[1])) {
            return false;
        }

        Integer hh = Integer.parseInt(dates[0]);
        Integer mm = Integer.parseInt(dates[1]);
        return !(hh < 0 || hh > 23 || mm < 0 || mm > 59);
    }
}
